#!/bin/bash
if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit 1
fi
##工作目录
gitdir=$PWD
logfile=/var/log/sftp_install.log
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe
 
##颜色变量!!
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

##功能定义!!
function print_status ()
{
    echo -e "\x1B[01;34m[*]\x1B[0m $1"
}

function print_good ()
{
    echo -e "\x1B[01;32m[成功]\x1B[0m $1"
}

function print_error ()
{
    echo -e "\x1B[01;31m[失败]\x1B[0m $1"
}

function print_notification ()
{
	echo -e "\x1B[01;33m[未知]\x1B[0m $1"
}

function error_check
{

if [ $? -eq 0 ]; then
	print_good "$1 成功完成."
else
	print_error "$1 失败. 请检查 $logfile 以获取更多详细信息."
exit 1
fi

}

function adduser(){
echo -e "${YELLOW} 请输入要添加的用户名?${NC}"
read user

# adduser --ingroup sftpgroup --shell /usr/sbin/nologin --disabled-password --gecos ""  $user
useradd -g sftpgroup -s /sbin/nologin -M $user
echo -e "${YELLOW} 请输入要设置的密码?${NC}"
read password
echo $password | passwd --stdin $user
#创建SFTP根目录
mkdir -p /data/$user
chown -R root:root /data/$user
chmod 755   /data/$user
mkdir /data/$user/uploads
chown $user:sftpgroup /data/$user/uploads
echo -e "$(date +"%Y%m%d %H:%M%S")\t用户名：$user\t密码：$password\n上传路径：/data/${user}/upload\n" >> /var/log/add_sftpUser_$(date +"%Y%m%d").log
echo "用户成功创建"
}


function baseconfig(){

#修改SFTP配置 
print_status "${YELLOW}修改SFTP配置${NC}"
##删除不需要的配置
sed -i "/X11Forwarding yes/d" /etc/ssh/sshd_config &>> $logfile 
sed -i "/X11DisplayOffset 10/d" /etc/ssh/sshd_config &>> $logfile 
sed -i "/sftp-server/d" /etc/ssh/sshd_config &>> $logfile 
##添加想要的配置
echo "Subsystem sftp internal-sftp" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
echo "Match group sftpgroup" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
echo "ChrootDirectory /data/%u" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
echo "X11Forwarding no" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
echo "AllowTcpForwarding no" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
echo "ForceCommand internal-sftp" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
# echo "Banner /etc/ssh/issue" | sudo tee -a /etc/ssh/sshd_config &>> $logfile 
touch /etc/ssh/sftp.lock 
}

function creatgroup(){
##创建SFTP组
  print_status "${YELLOW}为SFTP用户创建组${NC}"
  groupadd sftpgroup &>> $logfile 
  error_check 'SFTP用户组创建失败,可能已经被创建过'
}


if [ -f /etc/ssh/sftp.lock ];then
   echo -e "SFTP基础配置已经配置，请手工检查配置！"
else
   baseconfig
fi

egrep "^$group" /etc/group >& /dev/null  
if [ $? -ne 0 ]
then
creatgroup
else
adduser
fi

systemctl restart sshd &>> $logfile 
error_check 'SFTP配置'
print_status "${YELLOW}配置完成！.${NC}"







